<!-- <!DOCTYPE html> -->
<!-- <html lang="en">
    <head>-->
	
	    
		
		
        <title>Sequence Diagram Drag-n-drop</title>

        <script src="<?php echo base_url('/javascript/raphael.js');?>"></script>
	    <script src="<?php echo base_url('/javascript/jquery.js');?>"></script>
		
		<script src="<?php echo base_url('/javascript/raphael.serialize.js');?>"></script>
		<script src="<?php echo base_url('/javascript/raphael.export.js');?>"></script>
				
		<script src="<?php echo base_url('/javascript/json2.js');?>"></script>
		
		<script src="<?php echo base_url('/javascript/raphael.json.js');?>"></script>
		<script src="<?php echo base_url('/javascript/jsonify.js');?>"></script>
		<!-- <script src="customParser.js"></script> -->
		
        <script>
		    //Global variables
			var json;
			
			var flag = 0; // 0 = MOVE  ...... 1 = RESIZE
			var R;
			var downloadState;
			var currentState = -1; // for undo/redo
			
			//flags
			var dotted = false;
			var alt = false;
			var opt = false;
			var loop = false;
			
			// constants
			var rw = 10;
			var rh =  30;
			var rox = 100;
			var roy = 100;
			var drx = 250;
			var dx = 10;
			var dy = 30;
			var my = roy + dy;
			
			// global arrays to hold the conditional objects data
			
			var map = new Array(); // To store all the objects of drawn elements
			var idList = new Array();
			var history = new Array();
			var optList = new Array();   
			var loopList = new Array();
			var altList = new Array();
			
			
            window.onload = function () {
			    
                R = Raphael("diagram");
				//alert("width1:"+R.width + "  height1:" +R.height);
				//alert(document.getElementById("diagram").offsetHeight); 
				//alert("start");			     
			   
			   //parseUrl();
			   
			   function mydbclick()
			   {
			    x=document.forms["myForm"]["fname"].value;
				this.attr({text:x});
			   }
            
               function parseUrl()
			   {
			    //alert(window.location.pathname);
			   }
			
			};

             			
						
						
			function getDistance(pX,pY,qX,qY)
			{
			xs = pX - qX;
			xs = xs * xs;
			ys = pY - qY;
			ys = ys * ys;
			return Math.sqrt( xs + ys );
			}
			 
			
			function hide(e)
			{
			 obj1 = document.getElementById(e); 
			 obj1.style.display = 'none';
            }

			function show(e)
			{
			 obj1 = document.getElementById(e); 
			 obj1.style.display = 'block';
            }
			
			
			function exists(list,x)
			{
			 for(i in list)
			    {
				 if(list[i].text.attr("text") == x){return true;}
				}
			 return false;	
			}			
			
			function find(list,x)
			{
			 for(i in list)
			    {
				 if(list[i].text.attr("text") == x){return list[i];}
				}
			 return false;	
			}
			
			function setDotted()
			{dotted = true;}
			
			function UnsetDotted()
			{dotted = false;}
			
			
			function setOpt()
			{opt = true;}
			
			function UnsetOpt()
			{
			 opt = false;
			 var x = document.getElementById("option3");
			 x.style.backgroundColor="";
			 my = my + dy*2;
			 hide('endopt');
			}
			
			function setAlt()
			{alt = true;}
			
			function UnsetAlt()
			{
			 alt = false;
			 var x = document.getElementById("option4");
			 x.style.backgroundColor="";
             my = my + dy*2;
             hide('endalt');			 
			 hide('elsealt');
             hide('ifdalt');				 
			}
			
			function setLoop()
			{loop = true;}
			
			function UnsetLoop()
			{
			 loop = false;
			 var x = document.getElementById("option5");
			 x.style.backgroundColor="";
             my = my + dy*2;
             hide('endloop');			 
			}
			
			function hoverStart() 
			{
              //if (Raphael.type != 'VML') {    // Work-around loss of event handling on toFront().
                //        background.toFront();
                  //      foreground.toFront();
                     //}
             this.animate({opacity: 0.4, fill:"pink"}, 200);
            }
                
            function hoverEnd() 
			{
             this.animate({opacity: 1, fill:"white"}, 200);
            }
			
			function dbclicker()
			{
			 //alert("double clicked me");
			 
				 for(j in map)
				    {
					 if(map[j].ID == this.ID)
					   {
					    //alert("yepID: " + map[j].ID);
						loadData(map[j]);
						return;
					   }
					}
				 return false;
				
			}
            
			function loadData(object)
			{
			 //alert(object.text.attr("text"));
			 hide("form1");
			 show("editForm1");
			 document.forms["editForm1"]["id"].value = object.ID;
			 //alert(document.forms["editForm1"]["id"].value);
			 document.forms["editForm1"]["object1"].value = object.text.attr("text");
			 var x=document.getElementById("messages");
             //alert(x.selectedIndex);
             for(i in x)
               {
                //alert(x.selectedIndex);
                x.remove(i);
               }
			 //alert(object.msgList[0].text.attr("text"));  
			 for(i in object.msgList)
			    {
			     var opt = document.createElement("option");
                 opt.text = object.msgList[i].text.attr("text");
                 opt.value = i;
                 document.forms["editForm1"]["messages"].options.add(opt);
                }

            //var opt2 = document.createElement("option");
            //opt2.text = "Exc";
            //opt2.value = 2;
            //document.getElementById("").options.add(opt2);
			 
			}
			
			function submitChange()
			{
			 //alert("change submitted");
			 var id = document.forms["editForm1"]["id"].value;
			 //alert("id: "+id);
			 var name = document.forms["editForm1"]["object1"].value;
			 //var object;
			 
			 for(j in map)
				    {
					 if(map[j].ID == id)
					   {
					    var object = map[j];
						break;
					   }
					}
			 
			 var messageIndex = document.getElementById("messages").selectedIndex;
			 var newMessage = document.forms["editForm1"]["method"].value;
			 //alert("index:" + messageIndex);
			 if(messageIndex != -1){object.msgList[messageIndex].text.attr({text:newMessage});}
			 //var objName1 = document.forms["editForm1"]["method"].value = document.getElementById(m).options[messageIndex].text;
			 
             object.text.attr({text:name});
			 hide("editForm1");			 
			 
			 /*
			 var objName1 = document.forms["editForm1"]["object1"].value
			 var A = find(map,objName1);
		     for(i in A.msgList)
			   {
			    if(A.msgList[i].text.attr("text") = messageIndex)
			      {
				   A.msgList[i].text.attr(text:);
			      }
			   }
             
             alert(message);
			 */
             // TODO: showing the user the change occurblue with some glow or fancy input		 
             //alert(color);
             //alert(size);			 
             //object.text.animate({"fill":"blue","font-size":40}, 2000);
             //var anim = Raphael.animation({"text":name, "fill":"blue","font-size":20});
             //object.text.animate({"fill":"blue","font-size":40}); // run the given animation immediately
             //object.text.animate(anim.delay(1000)); // run the given animation after 500 ms			 
			 
			}
			
            function idGen()
            {
			 while(true)
			  {
			   var x = Math.floor((Math.random()*100)+1);
			   var t = idList.indexOf(x);
			   if(t==-1)
			     {
			      idList.push(x);
			      return x;
			     }
			  } 
			}			
                
			
			function validateInput()
			{
			
			}
			
			function submitForm1()
			{
			 //alert("hey");
			 
			 var objName1 = document.forms["form1"]["object1"].value;
			 var methodName = document.forms["form1"]["method"].value;
			 var objName2 = document.forms["form1"]["object2"].value;
			 var checkbx1 = document.forms["form1"]["checkbox1"].checked;
			 var checkbx2 = document.forms["form1"]["checkbox2"].checked;
			 
			 //validateInput(objName1,methodName,objName2);
			 
			 
			 var k = 1;; // constant to multitply text element result by for text positioning
						 

            if(!exists(map,objName1) && exists(map,objName2))
			    {alert("Not allowed, build left to right");}             
			
			else if(exists(map,objName1) && !exists(map,objName2))
			    { 
				  //alert("weird test");
				  
				  //R.circle(50,350,30);
				  
			      var A = find(map,objName1);
				  var sizeA = A.objList.length;
                  
				  var id2 = idGen();	
				  var text2 = R.text(rox, roy-dy, objName2).attr({fill:'blue', 'font-size':15,"font":"Arial", 'stroke-width':1 ,'text-anchor':'middle'});				  
                  var data1 = [["M", rox+rw/2, roy-5], ["L", rox+rw/2, my+dy*2]];
				  var timeline2 = R.path(data1).attr({ "stroke-width": 1, stroke: "black", 'arrow-end': 'classic', "stroke-dasharray": "- " });
                  var object2 = R.rect(rox, my, rw, rh).attr({fill: "white", stroke: "black", opacity: "none"});	
				  object2.ID = id2;				  
				  object2.hover(hoverStart, hoverEnd);
                  object2.dblclick(dbclicker);		
				  rox = rox + drx; // Make space for the new box to be drawn.
				  
				  var x1 = A.objList[sizeA-1].attr("x");
				  var x2 = object2.attr("x");
				  if(x1<=x2){x1 = x1 + dx;}
				  else{x2 = x2 + dx;k = -1;}
				  
				  var h1 = my-A.objList[sizeA-1].attr("y")+dy;
			      if(checkbx1)
				    {
                     my = my + dy; 					
					 //alert(checkbx1);
					 object1 = R.rect(A.objList[sizeA-1].attr("x"), my, rw, rh).attr({fill: "white", stroke: "black", opacity: "none"});
                     object1.ID = A.ID;				  
				     object1.hover(hoverStart, hoverEnd);
                     object1.dblclick(dbclicker);							 
					 A.objList.push(object1);
					 h1 = rh;
					}
				  
				  var data = [["M", x1, my], ["L", x2, my]];
				  data = [["M", x1, my], ["L", x2, my],["M", x2, my], ["L", x2-10, my-5],["M", x2, my], ["L", x2-10, my+5]];
                  if(dotted){ var message = R.path(data).attr({ "stroke-width": 2, stroke: "black" ,"stroke-dasharray": "- " });}
				  else{ var message = R.path(data).attr({ "stroke-width": 2, stroke: "black"});}		  
				  message.text = R.text(x1+250/2*k, my-10, methodName).attr({fill:'blue', 'font-size':12,"font":"Arial", 'stroke-width':1 ,'text-anchor':'middle'});
				  A.msgList.push(message);
				  my = my + dy;
				  
				  
				  var B = new Entity(text2, object2);
                  B.timeline = timeline2;
                  B.ID = id2;
                  B.msgList.push(message);				  
				  map.push(B);
				  
				  sizeA = A.objList.length;
				  
				  var A1 = A.objList[sizeA-1];
				  //var B1 = B.objList[sizeB-1];
				  A1.attr({height:h1});
				  //B1.attr({height:h2});
				}  
			
			
			else if(exists(map,objName1) && exists(map,objName2))
			    {
				  //alert("Already exists mate");
				  var A = find(map,objName1);
                  var B = find(map,objName2);
				  var sizeA = A.objList.length;
				  var sizeB = B.objList.length;

				  var x1 = A.objList[sizeA-1].attr("x");
				  var x2 = B.objList[sizeB-1].attr("x");
				  if(x1<=x2){x1 = x1 + dx;}
				  else{x2 = x2 + dx;k = -1;}
				  
				  var h1 = my-A.objList[sizeA-1].attr("y")+dy;
				  var h2 = my-B.objList[sizeB-1].attr("y")+dy;
				  //alert(h1);
				  
				  
				  
				  
				  if(checkbx1 || checkbx2) {my = my + dy;}
				  if(checkbx1)
				    {	
					 //alert(checkbx1);
					 object1 = R.rect(A.objList[sizeA-1].attr("x"), my, rw, rh).attr({fill: "white", stroke: "black", opacity: "none"});
                     object1.ID = A.ID;				  
				     object1.hover(hoverStart, hoverEnd);
                     object1.dblclick(dbclicker);							 
					 A.objList.push(object1);
					 h1 = rh;
					 my = my + dy;
					 h2 = my - B.objList[sizeB-1].attr("y");
					}
                  if(checkbx2)
				    {	
					 //alert(checkbx2);
					 object2 = R.rect(B.objList[sizeB-1].attr("x"), my, rw, rh).attr({fill: "white", stroke: "black", opacity: "none"});
                     object2.ID = B.ID;				  
				     object2.hover(hoverStart, hoverEnd);
                     object2.dblclick(dbclicker);						 
					 B.objList.push(object2);
					 h2 = rh;
					} 					
				  
			      var data = [["M", x1, my], ["L", x2, my]];
				  if(x1 > x2){data = [["M", x1, my], ["L", x2, my],["M", x2, my], ["L", x2+10, my-5],["M", x2, my], ["L", x2+10, my+5]];}
				  else { data = [["M", x1, my], ["L", x2, my],["M", x2, my], ["L", x2-10, my-5],["M", x2, my], ["L", x2-10, my+5]];}
				  //alert(A.text);
			    
    			  if(A.text.attr('text') == B.text.attr('text'))
				    {
					 //alert('yahoo');
					 data =[["M", x1, my], ["L", x1+10, my], ["L", x1+10, my-10], ["L", x1, my-10] ];
					 //drawSelfMessage();
					}
				  
				  if(dotted){ var message = R.path(data).attr({ "stroke-width": 2, stroke: "black", "stroke-dasharray": "- " });}
				  else{ var message = R.path(data).attr({ "stroke-width": 2, stroke: "black"});}
                  message.text = R.text(x1+250/2*k, my-10, methodName).attr({fill:'blue', 'font-size':12,"font":"Arial", 'stroke-width':1 ,'text-anchor':'middle'});
                  A.msgList.push(message);
				  B.msgList.push(message);
                  my = my + dy;				  

		          
				  
				  sizeA = A.objList.length;
				  sizeB = B.objList.length;
				  
				  var A1 = A.objList[sizeA-1];
				  var B1 = B.objList[sizeB-1];
				  A1.attr({height:h1});
				  data = A.timeline.attr("path");
				  data[1][2] = my+dy*2;
                  A.timeline.attr({path: data});				  
				  B1.attr({height:h2});
				  data = B.timeline.attr("path");
				  data[1][2] = my+dy*2;
                  B.timeline.attr({path: data});
		  
				}
            
				
            else if(!exists(map,objName1) && !exists(map,objName2))
			    {
              
				  //alert("Created A and B");
			      var id1 = idGen(); 
				  var id2 = idGen(); 
                  var text1 = R.text(rox, roy-dy, objName1).attr({fill:'blue', 'font-size':15,"font":"Arial", 'stroke-width':2 ,'text-anchor':'middle'});				  
				  var data = [["M", rox+rw/2, roy-5], ["L", rox+rw/2, my+dy*2]];
				  var timeline1 = R.path(data).attr({ "stroke-width": 1, stroke: "black", 'arrow-end': 'classic', "stroke-dasharray": "- " });				  
			      var object1 = R.rect(rox, roy, rw, rh).attr({fill: "white", stroke: "black", opacity: "none"});
				  object1.ID = id1;				  
				  object1.hover(hoverStart, hoverEnd);
                  object1.dblclick(dbclicker);				  
				  rox = rox + drx; // Make space for the new box to be drawn.


				  var text2 = R.text(rox,roy-dy, objName2).attr({fill:'blue', 'font-size':15,"font":"Arial", 'stroke-width':1 ,'text-anchor':'middle'});
                  data = [["M", rox+rw/2, roy-5], ["L", rox+rw/2, my+dy*2]];
				  var timeline2 = R.path(data).attr({ "stroke-width": 1, stroke: "black", 'arrow-end': 'classic', "stroke-dasharray": "- " });	
				  var object2 = R.rect(rox, my, rw, rh).attr({fill: "white", stroke: "black", opacity: "none"});
                  object2.ID = id2;
				  object2.hover(hoverStart, hoverEnd);
                  object2.dblclick(dbclicker);					  
				  rox = rox + drx; // Make space for the new box to be drawn.
				  
				  var x1 = object1.attr("x");
				  var x2 = object2.attr("x");
				  if(x1<=x2){x1 = x1 + dx;}
				  else{x2 = x2 + dx;k = -1;}
				  
				  data = [["M", x1, my], ["L", x2, my],["M", x2, my], ["L", x2-10, my-5],["M", x2, my], ["L", x2-10, my+5]];
                  if(dotted)
				    { 
					 var message = R.path(data).attr({ "stroke-width": 2, stroke: "black", "stroke-dasharray": "- " });
					}
				  else{ var message = R.path(data).attr({ "stroke-width": 2, stroke: "black"});}
				  message.text = R.text((x1+250/2*k), my-10, methodName).attr({fill:'blue', 'font-size':12,"font":"Arial", 'stroke-width':1 ,'text-anchor':'middle'});
				  my = my + dy;   // Change text coordinates to be relative to data!
				  //alert("Before creating objs");  
				  var A = new Entity(text1, object1);
				  var B = new Entity(text2, object2);
				  A.ID = id1;
				  A.timeline = timeline1;
				  B.timeline = timeline2;
				  B.ID = id2;
				  A.msgList.push(message);
				  B.msgList.push(message);
				  map.push(A);
				  map.push(B);
                 // alert(A.objList[0].text.attr("text"));				  
				}  
				
				
		    if(opt)
			 {
			  // TODO: Remember to disbla
			     
				 //alert('els');
				 var currentConditionBox = optList[optList.length-1].nameBoundry; 
				 var boxHeight = my - currentConditionBox.rect.attr('y');
				 currentConditionBox.rect.attr({height:boxHeight});
				 show("endopt");
			 }
			 
			 if(loop)
			 {
			  // TODO: Remember to disbla
			     
				 //alert('loop true');
				 var currentConditionBox = loopList[loopList.length-1].nameBoundry; 
				 var boxHeight = my - currentConditionBox.rect.attr('y');
				 currentConditionBox.rect.attr({height:boxHeight});
				 show("endloop");
			 }
			 
			 if(alt)
			 {
			  // TODO: Remember to disbla
			     
				 //alert('loop true');
				 var currentConditionBox = altList[altList.length-1].nameBoundry;
				 var boxHeight = my - currentConditionBox.rect.attr('y');
				 currentConditionBox.rect.attr({height:boxHeight});
				 show("ifalt");
				 show("elsealt");
				 show("endalt");
			 }
				
				
				//alert("after");
			 if((rox>750) || (my+dy*4>504) )	
			   { 
			    R.setSize(rox+dx*10, 700);
				//alert("widthLol:"+R.width+" heightLol:"+R.height);
                //alert(document.getElementById("diagram").offsetHeight); 				
               }
			 //alert("widthUp:"+R.width+" heightUp:"+R.height);  
             //history.push(R.toJSON());
             			 
             //history.push(objToJson(map,optList,loopList,altList));	
			 currentState++;			 
			 history[currentState] = objToJson(map,optList,loopList,altList);
			 history = history.slice(0,currentState+1);
			 //history.length = currentState + 1;
			 hide("form1");
			}
			
			function submitForm2()
			{
			 setOpt();
			 my = my + dy;
			 //alert('opt active');
			 var condition = document.forms["form2"]["condition"].value;
			 var nameBoundry = R.rect(15, my, 45,20).attr({fill: "white", stroke: "black", opacity: "none"});
			 nameBoundry.rect = R.rect(15, my, rox-drx+50, rh+10).attr({fill: "none", stroke: "black",'stroke-width':3,opacity: "none"});
			 nameBoundry.name = R.text(35,my+10,"OPT").attr({fill:'black', 'font-size':14,"font":"Arial", 'stroke-width':3 ,'text-anchor':'middle'});
			 nameBoundry.text = R.text(65,my+30,"["+condition+"]").attr({fill:'black', 'font-size':14,"font":"Arial", 'stroke-width':3 ,'text-anchor':'middle'});			 
			 //optList.push(new OptionObj(box,text));
			 optList.push(new OptionObj(nameBoundry));
		     my = my + dy;
			 //alert('opt created');
			 var x = document.getElementById("option3");
			 x.style.backgroundColor="blue";	
			 hide("form2");
			 disableAllBut("option3");
			 
			}
			
			function submitForm3()
			{
			 setAlt();
			 my = my + dy;
			 //alert('loop active');
			 var condition = document.forms["form3"]["condition"].value;
			 var nameBoundry = R.rect(15, my, 45,20).attr({fill: "white", stroke: "black", opacity: "none"});
			 nameBoundry.rect = R.rect(15, my, rox-drx+50, rh+10).attr({fill: "none", stroke: "black",'stroke-width':3,opacity: "none"});
			 nameBoundry.name = R.text(35,my+10,"ALT").attr({fill:'black', 'font-size':14,"font":"Arial", 'stroke-width':3 ,'text-anchor':'middle'});
			 nameBoundry.text = R.text(65,my+30,"["+condition+"]").attr({fill:'black', 'font-size':14,"font":"Arial", 'stroke-width':3 ,'text-anchor':'middle'});
			 altList.push(new AltObj(nameBoundry));
		     my = my + dy;
			 //alert('loop created');
			 var x = document.getElementById("option4");
			 x.style.backgroundColor="blue";	
			 hide("form3");
			 
			}
			
			function submitForm4()
			{
			 setLoop();
			 my = my + dy;
			 //alert('loop active');
			 var condition = document.forms["form4"]["condition"].value;
			 var nameBoundry = R.rect(15, my, 45,20).attr({fill: "white", stroke: "black", opacity: "none"});
			 nameBoundry.rect = R.rect(15, my, rox-drx+50, rh+10).attr({fill: "none", stroke: "black",'stroke-width':3,opacity: "none"});
			 nameBoundry.name = R.text(35,my+10,"LOOP").attr({fill:'black', 'font-size':14,"font":"Arial", 'stroke-width':3 ,'text-anchor':'middle'});
			 nameBoundry.text = R.text(65,my+30,"["+condition+"]").attr({fill:'black', 'font-size':14,"font":"Arial", 'stroke-width':3 ,'text-anchor':'middle'});			 
			 //optList.push(new OptionObj(box,text));
			 loopList.push(new LoopObj(nameBoundry));
		     my = my + dy;
			 //alert('loop created');
			 var x = document.getElementById("option5");
			 x.style.backgroundColor="blue";	
			 hide("form4");
			 
			}
			
			function toggleColor(color,notColor)
			{ 
			 var x = document.getElementById(color);
			 x.style.backgroundColor="blue";	
			 x = document.getElementById(notColor);
			 x.style.backgroundColor="";	 
			}
			
			function Entity(text, object)
			{
			 this.text = text;
			 
			 this.objList = new Array();
			 this.objList.push(object);
		
			 this.msgList = new Array();
			 //this.msgList.push(message);
			// map.push(this);
			
			}
			
			function OptionObj(nameBoundry)
			{
			 this.nameBoundry = nameBoundry;			 
			}
			
			function AltObj(nameBoundry)
			{
			 this.nameBoundry = nameBoundry;			 
			}
			
			function LoopObj(nameBoundry)
			{
			 this.nameBoundry = nameBoundry;			 
			}
			
			function putLineSeparationConditionBox()
			{
			 var obj = altList[altList.length-1].nameBoundry;
			 data = [["M", obj.rect.attr("x"), my], ["L", obj.rect.attr("x")+obj.rect.attr("width"), my]];
			 obj.line = R.path(data).attr({ "stroke-width": 2, stroke: "black"});
             var boxHeight = obj.rect.attr('height') + dy;
		     obj.rect.attr({height:boxHeight});
             my = my + dy*2;			 
			}
			
			
			function exportServerSide()
			{
			 var str =  new Array();
			 var temp = R.toSVG();
			 str.push({jsonsvg: temp});
			 //str = {temp;
			 str = JSON.stringify(str);
			 //alert(temp);
			 //alert(str);
			 //alert("GO");
			 str = temp;
			 if (str=="")
		       {
		        alert("Empty String!");
		        return;
		       } 
		     if (window.XMLHttpRequest)
		       {// code for IE7+, Firefox, Chrome, Opera, Safari
		        xmlhttp=new XMLHttpRequest();
		       }
		     else
		       {// code for IE6, IE5
		        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		       }
	       	 xmlhttp.onreadystatechange=function()
		       {
			    var remover;
				var flag = false;
			    if ((xmlhttp.readyState==1))
				 { 
				  var x = document.getElementById("export");
			      x.style.backgroundColor="blue";	/*remover = spinner("diagram", 70, 120, 12, 25, "black");*/flag=true;
				 }
				 
		        if (xmlhttp.readyState==4 && xmlhttp.status==200)
			      {
				   downloadState = true;
				   var x = document.getElementById("export");
			       x.style.backgroundColor="";	
				   alert("response: " + xmlhttp.responseText);		 
			       
				  }
		       }
			   
		     xmlhttp.open("POST","<?php echo base_url('/ajax/svgToPng.php');?>",true);
			 xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		     xmlhttp.send("data="+str);
			}
			
			
		
		function saveDiagram(str1)
		{
		//alert('save');
		json = objToJson(map,optList,loopList,altList);
		var str = new Array();
		str[0] = document.getElementById("diagramname").value;
		str[1] = json;
		//alert(<?php echo $this->session->userdata('user_id'); ?>);
		str[2] = <?php echo $this->session->userdata('user_id'); ?>;
		str = JSON.stringify(str);
		//var data ="[" +str+"]";
		//alert(data);
		//alert(json);
		if (str=="")
		  {
		  alert("Empty String!");
		  return;
		  } 
		if (window.XMLHttpRequest)
		  {// code for IE7+, Firefox, Chrome, Opera, Safari
		  xmlhttp=new XMLHttpRequest();
		  }
		else
		  {// code for IE6, IE5
		  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		  }
		xmlhttp.onreadystatechange=function()
		  {
		  if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
			 if(xmlhttp.responseText == 1)
			   {alert("Diagram saved Successfully");}
             			 
			}
		  }
		xmlhttp.open("POST","<?php echo base_url('/ajax/saveDiagram.php');?>",true);
	    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		xmlhttp.send("data="+str);
		}
		
		
		function fetchDiagram(name,userId)
		{
		//alert('start'+name);
		var str = new Array();
		str[0] = name;
		str[1] = userId;
		var data = JSON.stringify(str);
		
		if (str=="")
		  {
		  alert("Empty String!");
		  //return;
		  } 
		if (window.XMLHttpRequest)
		  {// code for IE7+, Firefox, Chrome, Opera, Safari
		  xmlhttp=new XMLHttpRequest();
		  }
		else
		  {// code for IE6, IE5
		  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		  }
		xmlhttp.onreadystatechange=function()
		  {
		  if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
			//alert("response");
			//alert(xmlhttp.responseText);
			jsonToObj(xmlhttp.responseText);
			//return xmlhttp.responseText; // It doesn't work if you return responseText
			}
		  }
		
		xmlhttp.open("GET","<?php echo base_url('/ajax/updateDB.php');?>?q="+data,true);  
		xmlhttp.send();
		}
		
		
		function login()
		{
		var str = new Array();
		str[0] = document.forms["editForm1"]["email"].value;
		str[1] = document.forms["editForm1"]["pass"].value;;
		if (str=="")
		  {
		  alert("Empty String!");
		  //return;
		  } 
		if (window.XMLHttpRequest)
		  {// code for IE7+, Firefox, Chrome, Opera, Safari
		  xmlhttp=new XMLHttpRequest();
		  }
		else
		  {// code for IE6, IE5
		  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		  }
		xmlhttp.onreadystatechange=function()
		  {
		  if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
			alert("response");
			alert(xmlhttp.responseText);
			jsonToObj(xmlhttp.responseText);
			//return xmlhttp.responseText; // It doesn't work if you return responseText
			}
		  }
		xmlhttp.open("GET","<?php echo base_url('/ajax/login_ajax.php');?>?q="+str,true);
		xmlhttp.send();
		}
		
		
		function saveToDB()
		{ 
		 <?php if(!$this->session->userdata('user_name')) : ?>
		    alert('Log in to be able to save your Diagram');
			return;
		 <?php endif; ?>	
		 alert('save');
		 json = objToJson(map,optList,loopList,altList);
		 saveDiagram(json);

		}
		
		function fetchFromDB(name,userId)
		{
         <?php if(!$this->session->userdata('user_name')) : ?>
		    alert('Log in to be able to load your Diagram');
			return;
		 <?php endif; ?>
         alert('Load Diagram: ' + name);		 
		 fetchDiagram(name,userId);
		}
		
function objToJson(list,optionList,looperList,alterList)
{
 var objects = new Array();
 for(i in list)
   {
    var rectList =  new Array();   
    var messages =  new Array();     
	
    var ID =  list[i].ID;
    var lifeline = list[i].timeline;
    var objList = list[i].objList;
	var text = list[i].text;
	var msgList = list[i].msgList;
	//var msgName = message.text;
	//alert('lifeline');
	//alert(lifeline);
	//alert('type');
	//alert(objList[0].attrs);
	for(j in objList)
      {
	   rectList.push({
                    type:      objList[j].type,
	                attrs:     objList[j].attrs
				    });
      }
	  //alert('rectList');
	  //alert(rectList);
	
	for(k in msgList)
      {
	   messages.push({
                    path:     msgList[k].attrs,
	                text:     msgList[k].text.attrs
				    });
      }
	
	objects.push({
	            lifeline:  lifeline.attrs,  
				ID:        ID,
				text:      text.attrs,
				rects:     rectList,
				msgs:      messages
				});
	//alert(objects);
    //alert('stringify');	
    
   }
   
 var options = new Array();  
 for(i in optionList)
   {
    options.push({
	            nameBoundry:   optionList[i].nameBoundry.attrs,
				rect:          optionList[i].nameBoundry.rect.attrs,
				name:          optionList[i].nameBoundry.name.attrs,
				text:          optionList[i].nameBoundry.text.attrs
				});   
   }
   
 var loops = new Array();   
 for(i in looperList)
   {
    loops.push({
				nameBoundry:   looperList[i].nameBoundry.attrs,
				rect:          looperList[i].nameBoundry.rect.attrs,
				name:          looperList[i].nameBoundry.name.attrs,
				text:          looperList[i].nameBoundry.text.attrs
				});   
   }

 var alts = new Array();   
 for(i in alterList)
   {
    alts.push({
				nameBoundry:   alterList[i].nameBoundry.attrs,
				rect:          alterList[i].nameBoundry.rect.attrs,
				name:          alterList[i].nameBoundry.name.attrs,
				text:          alterList[i].nameBoundry.text.attrs
				});
    if(typeof alterList[i].nameBoundry.line != 'undefined'){ alts.push({line: alterList[i].nameBoundry.line.attrs}); }				
   }    
   
   
   //alert(JSON.stringify(objects));
   var result = new Array();
   result.push(objects);
   result.push(options);   
   result.push(loops);
   result.push(alts);
   result.push(my);
   result.push(rox);
   //alert(JSON.stringify(result));
   return JSON.stringify(result);
}

//TODO: in the methods below of recreating the  raphael objects, need to
// try and get the "type" automatically NOT manually like now.

function jsonToObj(jsonFormat)
{
 json = JSON.parse(jsonFormat);
 var objJson = json[0];
 var optJson = json[1];
 var loopJson = json[2];
 var altJson = json[3];
 my = json[4];
 rox = json[5];
 
 //alert("optJson: " + optJson);
 //var loopJson;
 //var altJson;
 R.clear();
 R.setSize(rox,my+50);
 //alert("GO");
 var objects = new Array();
 
// map.length = 0;
 //optList.length = 0;
 //loopList.length = 0;
 map = [];
 optList = [];
 loopList = [];
 altList = [];
 
 for(i in objJson)
   {
	
	//alert(objJson[i].ID);
	
	var lifeline = R['path']().attr(objJson[i].lifeline);
	var ID = objJson[i].ID;
	var text = R['text']().attr(objJson[i].text);
	
	var A = new Entity(text,"");
	A.timeline = lifeline;
	A.ID = ID;
	
	for(j in objJson[i].rects)
	   {
        var rect = R['rect']().attr(objJson[i].rects[j].attrs).dblclick(dbclicker).hover(hoverStart, hoverEnd);	   
	    rect.ID = ID;// TODO: the "" when initializing Entity screws life up as it make an empty string at objList[0]
		A.objList[j] = rect;
		//else{A.objList.push(rect);} // TODO: temp solution = bad! Better don't initialize objList from Entity.
   	   }
	for(k in objJson[i].msgs)
	   {
        var msg = R['path']().attr(objJson[i].msgs[k].path);	   
	    msg.text = R['text']().attr(objJson[i].msgs[k].text);
		A.msgList.push(msg);
   	   }
	   
    //alert("length: " + map.length);	   
	map.push(A);
	//alert('push');	
   }
 for(i in optJson)
   {
    var nameBoundry = R['rect']().attr(optJson[i].nameBoundry);
    nameBoundry.rect = R['rect']().attr(optJson[i].rect);
	nameBoundry.name = R['text']().attr(optJson[i].name);
	nameBoundry.text = R['text']().attr(optJson[i].text);
    optList.push(new OptionObj(nameBoundry));
   }
   
 for(i in loopJson)
   {
    var nameBoundry = R['rect']().attr(loopJson[i].nameBoundry);
    nameBoundry.rect = R['rect']().attr(loopJson[i].rect);
	nameBoundry.name = R['text']().attr(loopJson[i].name);
	nameBoundry.text = R['text']().attr(loopJson[i].text);
    optList.push(new LoopObj(nameBoundry));
   }
   
 for(i in altJson)
   {
    var nameBoundry = R['rect']().attr(altJson[i].nameBoundry);
    nameBoundry.rect = R['rect']().attr(altJson[i].rect);
	nameBoundry.name = R['text']().attr(altJson[i].name);
	nameBoundry.text = R['text']().attr(altJson[i].text);
	if(typeof altJson[i].line != 'undefined'){nameBoundry.line = R['path']().attr(altJson[i].line);}
    altList.push(new AltObj(nameBoundry));
   }  
   
   
 //return objects; 

}		
		
		
        function undo()
		{
		 //alert("undo");
		 currentState--;
		 if(currentState==-1)
		   {currentState++;/*alert("Can't go furthur");*/return;}
		 R.clear();
		 jsonToObj(history[currentState]);
		
		}        
		
		function redo()
		{
		 //alert("redo");
		 currentState++;
		 if(currentState==history.length)
		   {currentState--;/*alert("Can't go furthur");*/return;}
		 R.clear();
		 //alert(currentState+" : "+history.length);
		 //alert(history[currentState]);
		 jsonToObj(history[currentState]);
		}  
		
		
		function iterateObjects()
		{
		 for(i in map)
			{
		     alert(map[i]);
		    }
		}


            function spinner(holderid, R1, R2, count, stroke_width, colour) {
                var sectorsCount = count || 12,
                    color = colour || "#fff",
                    width = stroke_width || 15,
                    r1 = Math.min(R1, R2) || 35,
                    r2 = Math.max(R1, R2) || 60,
                    cx = r2 + width,
                    cy = r2 + width,
                    r = Raphael(holderid, r2 * 2 + width * 2, r2 * 2 + width * 2),
					
                    
                    sectors = [],
                    opacity = [],
                    beta = 2 * Math.PI / sectorsCount,

                    pathParams = {stroke: color, "stroke-width": width, "stroke-linecap": "round"};
                    Raphael.getColor.reset();
					
                for (var i = 0; i < sectorsCount; i++) {
                    var alpha = beta * i - Math.PI / 2,
                        cos = Math.cos(alpha),
                        sin = Math.sin(alpha);
                    opacity[i] = 1 / sectorsCount * i;
                    sectors[i] = r.path([["M", cx + r1 * cos, cy + r1 * sin], ["L", cx + r2 * cos, cy + r2 * sin]]).attr(pathParams);
                    if (color == "rainbow") {
                        sectors[i].attr("stroke", Raphael.getColor());
                    }
                }
                var tick;
                (function ticker() {
                    opacity.unshift(opacity.pop());
                    for (var i = 0; i < sectorsCount; i++) {
                        sectors[i].attr("opacity", opacity[i]);
                    }
                    r.safari();
					if(checkDownloadState()){r.remove();}
                    tick = setTimeout(ticker, 1000 / sectorsCount);
                })();
                return function () {
                    clearTimeout(tick);
                    r.remove();
                };
            }

			function checkDownloadState()
			{
			 if(downloadState==true){downloadState=false;return true}
			 else {return false;}
			}

			function disableAllBut(e)
			{
			 document.getElementById("option3").disabled = true;
			 document.getElementById("option4").disabled = true;
			 document.getElementById("option5").disabled = true;
			}
			
			function enableAllBut(e)
			{
			 document.getElementById("option3").disabled = false;
			 document.getElementById("option4").disabled = false;
			 document.getElementById("option5").disabled = false;
			}
			
			function editMessage(m) 
			{
			// alert('db1');
			 var messageIndex = document.getElementById(m).selectedIndex;
			 var objName1 = document.forms["editForm1"]["method"].value = document.getElementById(m).options[messageIndex].text;
			 			 
			}

			function testOutput()
			{
			 alert("currrentState: " + currentState);
			 alert("length: " + history.length);
			 alert(history[currentState]);
			 alert(map.length);
			 for(i in history)
			 {
			 alert("snap1: "+ i);
			 alert(history[i]);
			 jsonToObj(history[i]);
			 }
			}
		
			</script>
			
			
			
    </head>

	
    <body>
	    
        
        
		
		<div id="toolbox" >
		<button id="option1" type="button" onclick="UnsetDotted();hide('editForm1');hide('form2');hide('form3');hide('form4');show('form1')"> 
		<img class="optionimage" src="<?php echo base_url('/images/option1.png');?>" ></button><br><br>
		<button  id="option2" type="button" onclick="setDotted();hide('editForm1');hide('form2');hide('form3');hide('form4');show('form1')"> 
		<img class="optionimage" src="<?php echo base_url('/images/option2.png');?>" ></button><br><br>
        <button id="option3" type="button" onclick="hide('editForm1');hide('form1');hide('form3');hide('form4');show('form2')"> 
		<img class="optionimage" src="<?php echo base_url('/images/optionOpt.png');?>" ></button><br><br>
		<button  id="option4" type="button" onclick="hide('editForm1');hide('form1');hide('form2');hide('form4');show('form3')"> 
		<img class="optionimage" src="<?php echo base_url('/images/optionAlt.png');?>" ></button><br><br>
		<button id="option5" type="button" onclick="hide('editForm1');hide('form1');hide('form2');hide('form3');show('form4')"> 
		<img class="optionimage" src="<?php echo base_url('/images/optionLoop.png');?>" ></button>
		</div>
		
		<div id="inputbox" >
		<h1 style="text-align:center">Input Box </h1>
		Diagram Name <input id="diagramname" type="text" name="user" size="13">
		<form class="inputform" id="form1" name="input"  method="post" >
		<br>A: <input id="object1" type="text" name="user" size="13">
		<input id="checkbox1" type="checkbox" name="new" value="new">New<br><br>
		B: <input id="object2" type="text" name="user" size="13">
		<input id="checkbox2" type="checkbox" name="new" value="new">New<br><br>
		Method: <input id="method" type="text" name="user" size="13"><br><br>
		<input type="button" value="Done" onclick="submitForm1()" >
		</form>
		
		<form class="inputform" id="form2" name="input"  method="post"  >Opt
		<br>Condition: <input id="condition" type="text" name="user" size="13"><br><br>
		<!-- Start: <select id="startcondition" name="messages" size="1" style="width:200;">
		<option value="default" selected="selected">A</option>
		</select><br>
		End: <select id="startcondition" name="messages" size="1" style="width:200;"> 
		<option value="default" selected="selected">B</option>
		</select><br><br> -->
		<input type="button" value="Done" onclick="submitForm2()" ><br>
		</form>
		<input class="hiddenbutton" id="endopt" type="button" value="end" onclick="UnsetOpt();enableAllBut('')" >
		
		<form class="inputform" id="form3" name="input"  method="post" >Alt
		<br>Condition: <input id="condition" type="text" name="user" size="13"><br><br>
		<!-- Start: <select id="startcondition" name="messages" size="1" style="width:200;">
		<option value="default" selected="selected">A</option>
		</select><br>
		End: <select id="startcondition" name="messages" size="1" style="width:200;"> 
		<option value="default" selected="selected">B</option>
		</select><br><br> -->
		<input type="button" value="Done" onclick="submitForm3()" ><br>
		</form>
		<input class="hiddenbutton" id="endalt" type="button" value="end" onclick="UnsetAlt();enableAllBut('')"  >
		<input class="hiddenbutton" id="elsealt" type="button" value="else" onclick="toggleColor('elsealt','ifalt');putLineSeparationConditionBox()"   >
		<input class="hiddenbutton" id="ifalt" type="button" value="if"  >
		
		
		<form class="inputform" id="form4" name="input"  method="post"  >Loop
		<br>Condition: <input id="condition" type="text" name="user" size="13"><br><br>
		<!-- Start: <select id="startcondition" name="messages" size="1" >
		<option value="default" selected="selected">A</option>
		</select><br>
		End: <select id="startcondition" name="messages" size="1" >
		<option value="default" selected="selected">B</option>
		</select><br><br> -->
		<input type="button" value="Done" onclick="submitForm4()" ><br>
		</form>
		<input class="hiddenbutton" id="endloop" type="button" value="end" onclick="UnsetLoop();enableAllBut('')"  >
		
		
		<form class="inputform" id="editForm1" name="input"  method="post" >
		<input id="id" type="text" name="user" size="13" style="display:none" >
		<br>Name: <input id="object1" type="text" name="user" size="13"><br><br>
		<select id="messages" name="messages" size="5" onclick="editMessage('messages')" >
		<option value="default" selected="selected">Method:</option>
		</select><br><br>
		<input id="method" type="text" name="user" size="13"><br><br>
		<input type="button" value="Done" onclick="submitChange()" >
		</form>
        </div>
		 
		
		<div id="buttones" >
		<button id="undo"   type="button" value="Undo" onclick="undo()" > 
		<img class="buttonsimage" src="<?php echo base_url('/images/undo.png');?>" ></button>
		<button  id="redo"   type="button" value="Redo" onclick="redo()" >
		<img class="buttonsimage" src="<?php echo base_url('/images/redo.png');?>" ></button>
		<input id="save"   type="button" value="Save" onclick="saveToDB()" >
		<input id="fetch"  type="button" value="export2" onclick="export2()" >
		<input id="export" type="button" value="Export" onclick="exportServerSide()" >
		<!--<input id="test"   type="button" value="Tester" onclick="testOutput()" >-->
		</div>
		
		<div id="userdata">
		<?php if(!$this->session->userdata('user_name')) : ?>
			<div class="signin_form">
			<h1 style="text-align:center">Login</h1>
			<?php echo form_open("user/login"); ?>
			<label for="email"></label>
			<input type="text" id="email" name="email" value="Email" onFocus="if(this.value == 'Email'){this.value=''}"  onblur="if(this.value == ''){this.value='Email'}"/>
			
			<label for="password"></label>
			<input type="password" id="pass" name="pass" value="Password" onFocus="if(this.value == 'Password'){this.value=''}"  onblur="if(this.value == ''){this.value='Password'}"/ />
			</p>
			<input type="submit" class="" value="Log in"  />
			</p>
			<?php echo form_close(); ?>
			</div><!--<div class="signin_form">-->
			
			<div class="reg_form">
			<h1 style="text-align:center">Register</h1>
			<div style="text-align:center;color:red;"> <?php echo validation_errors('<p class="error">'); ?></div>
			 <?php echo form_open("user/registration"); ?>
			  <p>
			  <label for="user_name"></label>
			  <input type="text" id="user_name" name="user_name" value="Name"  onFocus="if(this.value == 'Name'){this.value=''}"  onblur="if(this.value == ''){this.value='Name'}" />
			  </p>
			  <p>
			  <label for="email_address"></label>
			  <input type="text" id="email_address" name="email_address" value="Email Address"  onFocus="if(this.value == 'Email Address'){this.value=''}"  onblur="if(this.value == ''){this.value='Email Address'}" />
			  </p>
			  <p>
			  <label for="password"></label>
			  <input type="password" id="password" name="password" value="0000000" onFocus="if(this.value == '0000000'){this.value=''}"  onblur="if(this.value == ''){this.value='0000000'}" />
			  </p>
			  <p>
			  <label for="con_password"></label>
			  <input type="password" id="con_password" name="con_password" value="1111111" onFocus="if(this.value == '0000000'){this.value=''}"  onblur="if(this.value == ''){this.value='0000000'}" />
			  </p>
			  <p>
			  <input type="submit" class="greenButton" value="Submit" />
			  </p>
			 <?php echo form_close(); ?>
			</div><!--<div class="reg_form">-->
			</div><!--<div id="content">-->
			
        <?php else : ?>
			<div class="contenta">
			  <h2>Welcome <?php echo $this->session->userdata('user_name'); ?>!</h2>
			  <p>This section represents the area that only logged in members can access.</p>
			  <h4><?php echo anchor('user/logout', 'Logout'); ?></h4>
			  <table class="info-table" border="1">
					<tr>
						
						<th>Diagram Name</th>
						<th>Date Created</th>
						<th></th>
					</tr>
					
                    
			<?php foreach($diagramData as $value) {	 ?>
					<tr>
						<td><a href="javascript:fetchFromDB('<?php echo $value['diagram_name'];?>',5)"><?php echo $value['diagram_name'];?></a></td>
						<td><?php echo $value['diagram_id'];?></td>
					</tr>
			<?php } ?>                    					
							
					
				</table>
			  
			</div><!--<div class="content">-->
        <?php endif; ?>			
		</div>
		
		<div id="diagram">

		</div>
		
		
				
    </body>
<!--</html>-->